package com.ww.companyCabinetSystem.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ww.companyCabinetSystem.constant.BaseConstant;
import com.ww.companyCabinetSystem.constant.ThreadPool;
import com.ww.companyCabinetSystem.model.vo.LogMessageVo;
import com.ww.companyCabinetSystem.model.vo.UserInfoVo;
import com.ww.companyCabinetSystem.thread.WriteLogRunnable;
import com.ww.companyCabinetSystem.utils.JsonUtil;

/**
 * 登陆拦截器.
 * 
 * @author zidu 2015年12月21日
 */
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {
	
	private Logger log = LogManager.getLogger(LoginHandlerInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		UserInfoVo userInfo = (UserInfoVo) request.getSession().getAttribute(
				"LoginUserInfo");

		if (request.getServletPath().startsWith("/AdminController")
				|| request.getServletPath().startsWith("/Error")
				|| request.getServletPath().startsWith("/Content")
				|| request.getServletPath().startsWith("/i18n")) {
			return true;
		}

		if (null != userInfo) {
			return true;
		}

		response.sendRedirect(request.getContextPath());
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		try {
			UserInfoVo userInfo = (UserInfoVo) request.getSession().getAttribute(
					"LoginUserInfo");
			//异步记日志
			LogMessageVo vo = new LogMessageVo();
			if (null != userInfo){
				vo.setStatusCode(BaseConstant.LOGSTATUS_INFO);
				vo.setMethodName(request.getServletPath());
				vo.setMessage(JsonUtil.toJson(userInfo));
			} else {
				
			}
			ThreadPool.getInstance().loadTasks(new WriteLogRunnable(vo));
		} catch (Exception e) {

		}
	}
}
